package authority.dao;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import authority.entity.Role;
import authority.util.DbBuilder;
/**
 * 角色dao
 * @author shichenyang
 *
 */
public class RoleDao {
	/**
	 * 查询所有的角色
	 * @return
	 */
	public List<Role> findAllList(){
		StringBuffer sb = new StringBuffer();
		sb.append("select * from role");
		return DbBuilder.getListBean(sb.toString(), Role.class);
	}

	/**
	 * 分页查询角色讯息
	 * @param start
	 * @param length
	 * @param role
	 * @return
	 */
	public List<Role> findListByPage(Integer start, Integer length, Role role) {
		StringBuffer sb = new StringBuffer();
		sb.append("select * from role");
		sb.append(" where 1=1");
		List<Object> o = new ArrayList<Object>();
		if (role.getName() != null && !role.getName().isEmpty()) {
			sb.append(" and name like concat('%',?,'%')");
			o.add(role.getName());
		}
		sb.append(" order by update_time desc");
		sb.append(" limit ?,?");
		o.add(start);
		o.add(length);

		return DbBuilder.getListBean(sb.toString(), Role.class, o.toArray());
	}

	/**
	 * 获取查询的数量
	 * @param role
	 * @return
	 */
	public Integer findAllCount(Role role) {
		StringBuffer sb = new StringBuffer();
		sb.append("select count(*) from role");
		sb.append(" where 1=1");
		List<Object> o = new ArrayList<Object>();
		if (role.getName() != null && !role.getName().isEmpty()) {
			sb.append(" and name like concat('%',?,'%')");
			o.add(role.getName());
		}
		return DbBuilder.getCount(sb.toString(), o.toArray());
	}

	/**
	 * 添加一个角色
	 * @param role
	 * @param connection
	 * @return
	 */
	public Integer addRole(Role role, Connection connection) {
		String sql = "insert into role values(?,?,?,?,?,?,?)";
		return DbBuilder.save(connection, sql, role.getId(), role.getName(),
				role.getRemarks(), role.getCreateTime(), role.getUpdateTime(),
				role.getOper(), role.getStatus());
	}
}
